from typing import Any, List, Optional

from fastapi import APIRouter, Depends, HTTPException, status, Query
from fastapi_pagination import Page
from pydantic.types import UUID4
from sqlalchemy.orm import Session

from app import crud, models, schemas
from app.api import deps
from app.models.TaskClassificationLibrary import TaskClassificationLibrary
router = APIRouter()


@router.get("/search", summary="检索任务分类库")
async def read_task_classification_libraries(
        search_key: Optional[str] = None,
        db: Session = Depends(deps.get_db),
        page_size: int = Query(10, alias="page_size"),  # 每页显示多少条数据
        current_page: int = Query(1, alias="current_page")  # 当前页码
        # skip: int = 0,
        # limit: int = 100,
        # current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    检索当前用户的任务分类库。管理员用户检索所有任务分类库。
    """
    try:
        query = db.query(TaskClassificationLibrary)
        if search_key:
            query = query.filter(TaskClassificationLibrary.category_name.ilike(f"%{search_key}%"))

        # 计算总记录数
        total = query.count()
        results = query.offset((current_page - 1) * page_size).limit(page_size).all()
        # results = paginate(query)
        items = []
        for result in results:
            updated_at = result.updated_at if result.updated_at else result.created_at
            result.updated_at = updated_at.strftime("%Y年%m月%d日 %H:%M:%S")
            result.created_at = result.created_at.strftime(
                "%Y年%m月%d日 %H:%M:%S")
            items.append({
                "id": result.id,
                "category_name": result.category_name,
                "usage_count": result.usage_count,
                "created_at": result.created_at,
                "updated_at": result.updated_at,
            })
        final_result = {"total": total, "page": current_page, "size": page_size, "items": items}

        return final_result
        # if current_user.is_admin:
            # task_classification_libraries = crud.task_classification_library.get_multi(db, skip=skip, limit=limit)
            # task_classification_libraries = crud.task_classification_library.get_paginate(db)
        # else:
        #     # task_classification_libraries = crud.task_classification_library.get_multi(db, skip=skip, limit=limit)
        #     task_classification_libraries = crud.task_classification_library.get_paginate_by_user(
        #         db, user=current_user
        #     )
        # for task_classification_library in task_classification_libraries.items:
        #     updated_at = task_classification_library.updated_at if task_classification_library.updated_at else task_classification_library.created_at
        #     task_classification_library.updated_at = updated_at.strftime("%Y年%m月%d日 %H:%M:%S")
        #     task_classification_library.created_at = task_classification_library.created_at.strftime("%Y年%m月%d日 %H:%M:%S")
        # return task_classification_libraries
    except Exception as e:
        # 引发HTTP 500，表示请求无效
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )


@router.post("/", response_model=schemas.TaskClassificationLibrary, summary="创建任务分类库")
async def create_task_classification_library(
        *,
        db: Session = Depends(deps.get_db),
        task_classification_library_in: schemas.TaskClassificationLibraryCreate,
        # current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    创建新任务分类库。
    """
    try:
        # 检查是否存在同名分类
        existing_task = crud.task_classification_library.get_by_category_name(db, name=task_classification_library_in.category_name)

        if existing_task:
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail="系统中已存在具有此名称的分类",
            )
        task_classification_library = crud.task_classification_library.create(db=db, obj_in=task_classification_library_in)
        return task_classification_library
    except Exception as e:
        # 引发HTTP 500，表示请求无效
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

#
# @router.post("/admin", response_model=schemas.TaskClassificationLibrary, summary="创建任务分类库（管理员）")
# async def create_task_classification_library_admin(
#         *,
#         db: Session = Depends(deps.get_db),
#         task_classification_library_in: schemas.TaskClassificationLibraryCreate,
#         _: models.User = Depends(deps.get_current_admin_user),
#         user_id: UUID4,
# ) -> Any:
#     """
#     ADMIN: 为其他用户创建任务分类库。
#     """
#     try:
#         user = crud.user.get(db=db, id=user_id)
#         if not user:
#             raise HTTPException(
#                 status_code=status.HTTP_404_NOT_FOUND, detail="用户未找到"
#             )
#         task_classification_library = crud.task_classification_library.create_with_user(db=db,
#                                                                                         obj_in=task_classification_library_in,
#                                                                                         user=user)
#         return task_classification_library
#     except Exception as e:
#         # 引发HTTP 500，表示请求无效
#         raise HTTPException(
#             status_code=500,
#             detail=str(e)
#         )

@router.put("/{id}", response_model=schemas.TaskClassificationLibrary, summary="更新任务分类库")
async def update_task_classification_library(
        *,
        db: Session = Depends(deps.get_db),
        id: UUID4,
        task_classification_library_in: schemas.TaskClassificationLibraryUpdate,
        # current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    更新任务分类库。
    """
    try:
        task_classification_library = crud.task_classification_library.get(db=db, id=id)
        if not task_classification_library:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail="任务分类库未找到"
            )
        task_classification_library = crud.task_classification_library.update(db=db, db_obj=task_classification_library,
                                                                              obj_in=task_classification_library_in)
        return task_classification_library
    except Exception as e:
        # 引发HTTP 500，表示请求无效
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

# 添加新的关键字检索接口
# @router.get("/searchkey", response_model=Page[schemas.TaskClassificationLibrary], summary="通过关键字检索任务分类库")
# async def search_task_classification_libraries(
#     keyword: str = Query(...),
#     db: Session = Depends(deps.get_db),
#     current_user: models.User = Depends(deps.get_current_user)
# ) -> Any:
#     """
#     通过关键字检索任务分类库。管理员用户检索所有任务分类库，普通用户只检索自己的任务分类库。
#     """
#     try:
#         # print(keyword)
#         if current_user.is_admin:
#
#             # task_classification_libraries = crud.task_classification_library.get_by_keyword(db=db, keyword=keyword)
#             task_classification_libraries = crud.task_classification_library.get_key_paginate(
#                 db, keyword=keyword
#             )
#         else:
#             task_classification_libraries = crud.task_classification_library.get_key_paginate_by_user(
#                 db, user=current_user, keyword=keyword
#             )
#         for task_classification_library in task_classification_libraries.items:
#             updated_at = task_classification_library.updated_at if task_classification_library.updated_at else task_classification_library.created_at
#             task_classification_library.updated_at = updated_at.strftime("%Y年%m月%d日 %H:%M:%S")
#             task_classification_library.created_at = task_classification_library.created_at.strftime(
#                 "%Y年%m月%d日 %H:%M:%S")
#
#         return task_classification_libraries
#     except Exception as e:
#         # 引发HTTP 500，表示请求无效
#         raise HTTPException(
#             status_code=500,
#             detail=str(e)
#         )


@router.get("/{id}", summary="获取任务分类库详情")
async def read_task_classification_library(
        *,
        db: Session = Depends(deps.get_db),
        id: UUID4,
        # current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    按ID获取任务分类库。
    """
    try:
        task_classification_library = crud.task_classification_library.get(db=db, id=id)
        if not task_classification_library:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail="任务分类库未找到"
            )
        if task_classification_library:
            updated_at = task_classification_library.updated_at if task_classification_library.updated_at else task_classification_library.created_at
            task_classification_library.updated_at = updated_at.strftime("%Y年%m月%d日 %H:%M:%S")
            task_classification_library.created_at = task_classification_library.created_at.strftime("%Y年%m月%d日 %H:%M:%S")
        result = {}
        result["id"] = task_classification_library.id
        result["category_name"] = task_classification_library.category_name
        result["usage_count"] = task_classification_library.usage_count
        result["created_at"] = task_classification_library.created_at
        result["updated_at"] =  task_classification_library.updated_at

        return result
    except Exception as e:
        # 引发HTTP 500，表示请求无效
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )


@router.delete("/{id}", response_model=schemas.TaskClassificationLibrary, summary="删除任务分类库")
async def delete_task_classification_library(
        *,
        db: Session = Depends(deps.get_db),
        id: UUID4,
        # current_user: models.User = Depends(deps.get_current_user),
) -> Any:
    """
    按ID删除任务分类库。
    """
    try:
        task_classification_library = crud.task_classification_library.get(db=db, id=id)
        if not task_classification_library:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND, detail="任务分类库未找到"
            )
        task_classification_library = crud.task_classification_library.remove(db, obj=task_classification_library)
        return task_classification_library
    except Exception as e:
        # 引发HTTP 500，表示请求无效
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

@router.get("/unique_categories/", response_model=List[str], summary="获取播报任务分类名称的不重复列表")
async def get_unique_categories(
    db: Session = Depends(deps.get_db),
    # current_user: models.User = Depends(deps.get_current_user),
) -> List[str]:
    """
    获取分类名称的不重复列表。
    """
    try:
        categories = crud.task_classification_library.get_unique_categories(db=db)
        return categories
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
